package com.lumis.utils;

import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.springframework.stereotype.Component;

@Component
public class JSONUtils {

	/**
	 * Pasa cualquier objeto a Strin (JSON) para que pueda ser mapeado por js.
	 * */
	public String convertirAJSON(Object o) {

		ObjectMapper mapper = new ObjectMapper();

		Writer strWriter = new StringWriter();

		try {

			mapper.writeValue(strWriter, o);

		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return strWriter.toString();
	}

	public <T> List<T> mapJsonToObjectList(T typeDef, String json,@SuppressWarnings("rawtypes") Class clazz) throws Exception {
		List<T> list;
		ObjectMapper mapper = new ObjectMapper();
		TypeFactory t = TypeFactory.defaultInstance();
		list = mapper.readValue(json,
				t.constructCollectionType(ArrayList.class, clazz));
		return list;
	}

}
